
var express = require('express');
var ArticleProvider = require('./articleprovider-memory').ArticleProvider;
var app = express();

// log requests
app.use(express.logger('dev'));
app.use(express.favicon());
app.use(express.cookieParser());
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);


app.configure('development',function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
    app.use(express.errorHandler());
});

var articleProvider = new ArticleProvider('localhost', 27017);


app.get('/', function(req, res){
    articleProvider.findAll(function(error, docs){
        //res.send(docs);
        res.render('index.jade', { articles: docs });
    })
});

app.get('/blog/new', function(req,res){
    res.render('blog_new.jade',{title: 'New post'});
});

app.post('/blog/new', function(req, res){
    articleProvider.save({
        title: req.param('title'),
        body: req.param('body')
    }, function( error, docs) {
        res.redirect('/')
    });
});

app.get('/blog/:id', function(req, res) {
    articleProvider.findById(req.params.id, function(error, article) {
        res.render('blog_show.jade',
            {
                title: article.title,
                article:article
            });
    });
});

app.post('/blog/addComment', function(req, res) {
    articleProvider.addCommentToArticle(req.param('_id'), {
        person: req.param('person'),
        comment: req.param('comment'),
        created_at: new Date()
    } , function( error, docs) {
        res.redirect('/blog/' + req.param('_id'))
    });
});


// /files/* is accessed via req.params[0]
// but here we name it :file
app.get('/files/:filename(*)', function(req, res, next){
    var filename = req.params.filename
        , path = __dirname + '/files/' + filename;

    res.download(path);
});

app.get('/readcookie',function(req,res){
    res.send('req.cookies.name:' + req.cookies.name);
});

app.get('/writecookie',function(req,res){
    res.cookie('name', 'I\'m a cookie', 60000);
    res.send("cookie saved");
});

app.listen(3000);
console.log('listening on port 3000');
